<?php

if (!defined('BASEPATH'))
    exit('No direct script access allowed');

/**
 * @author Anh Nguyen <duyanhnguyen@vccorp.vn>
 * @copyright 2012
 */
class Upload extends MX_Controller
{

    public function __construct()
    {
        parent::__construct();
        $this->load->library('Myvietstring');
    }

    public function index()
    {
        $data = array();
        $pathUpload = FCPATH . PATH_UPLOAD . 'images/';
        $img_size = unserialize(IMG_SIZE);
        if (isset($_FILES['Filedata']['name'])) {
            $infoFile = getimagesize($_FILES['Filedata']['tmp_name']);
            $fileType = $infoFile['mime'];
            $data['errors'] = '';
            if ($fileType == 'image/pjpeg' || $fileType == 'image/jpeg') {
                $filename = $_FILES['Filedata']['name'];
                $pos = strrpos($filename, '.');
                $name = substr($filename, 0, $pos);
                $name = strtolower(str_replace(' ', '-', $this->myvietstring->removeVietChars($name)));
                $name = $this->myvietstring->removeInvalidCharacter($name);
                $name = strlen(strlen($name) > 10) ? substr($name, 0, 10) : $name;
                $name.= '-' . time();
                $normalSize = $img_size['normal'];
                $this->load->library('Myimage');
                $this->myimage->resizeFromWidthAndHeight($_FILES['Filedata']['tmp_name'], $normalSize['width'], $normalSize['height'], $pathUpload . $name . IMAGE_TYPE);
                if (is_file($_FILES['Filedata']['tmp_name']))
                    @unlink($_FILES['Filedata']['tmp_name']);
                $data['img_name'] = $name . IMAGE_TYPE;
                $data['link_img'] = '/uploads/images/' . $data['img_name'];
            } else {
                $data['errors'] = "Bạn chỉ được upload file ảnh định dạng jpeg, jpg";
            }
        }

        echo json_encode($data);
    }

}

?>
